/*
 * @Descripttion:
 * @version:
 * @Author: hhy
 * @Date: 2021-02-20 09:25:01
 * @LastEditors: hhy
 * @LastEditTime: 2021-02-20 10:50:27
 * @FilePath: \vue3-dome\src\utils\storage.ts
 */
const TokenKey = "User-Token";
const prefix = "userweb_";

export function getToken(): any {
  // 总后台带入使用的Token
  if (window.sessionStorage.getItem("userweb_Token")) {
    return JSON.parse(window.sessionStorage.getItem("userweb_Token"));
  }
  return localStorage.getItem(TokenKey);
}

export function setToken(token: any): void {
  return localStorage.setItem(TokenKey, token);
}

export function removeToken(): any {
  return localStorage.removeItem(TokenKey);
}

export function getItem(key: string) {
  return JSON.parse(window.sessionStorage.getItem(prefix + key));
}

export function setItem(key: string, data: any) {
  window.sessionStorage.setItem(prefix + key, JSON.stringify(data));
}

export function removeItem(key: string) {
  sessionStorage.removeItem(prefix + key);
}

//设置过期时间
Storage.prototype.setExpire = (key, value, expire) => {
  const obj = {
    data: value,
    time: Date.now(),
    expire: expire,
  };
  //localStorage 设置的值不能为对象,转为json字符串
  localStorage.setItem(key, JSON.stringify(obj));
};
Storage.prototype.getExpire = (key) => {
  let val: any = localStorage.getItem(key);
  if (!val) {
    return val;
  }
  val = JSON.parse(val);
  if (Date.now() - val.time > val.expire) {
    localStorage.removeItem(key);
    return null;
  }
  return val.data;
};
